// 本地存储管理系统
class StorageManager {
    constructor() {
        try {
            this.storageKey = 'zombieSchoolSurvival';
            this.version = '1.0';
            this.defaultData = this.createDefaultData();
            console.log('StorageManager 构造成功');
        } catch (error) {
            console.error('StorageManager 构造失败:', error);
            throw error;
        }
    }
    
    createDefaultData() {
        return {
            version: this.version,
            player: {
                name: 'Player',
                totalScore: 0,
                highScore: 0,
                gamesPlayed: 0,
                totalKills: 0,
                favoriteWeapon: 'pistol'
            },
            progress: {
                currentLevel: 1,
                maxLevelReached: 1,
                levelsCompleted: [],
                totalPlayTime: 0,
                lastPlayed: null
            },
            achievements: {
                firstKill: false,
                levelComplete: false,
                perfectLevel: false,
                weaponMaster: false,
                survivor: false,
                speedRunner: false,
                headHunter: false,
                unstoppable: false,
                sharpShooter: false,
                berserker: false,
                collector: false,
                invincible: false,
                bossSlayer: false,
                chainKiller: false,
                noReload: false,
                oneShotOneKill: false,
                doubleDown: false,
                tripleKill: false,
                megaKill: false,
                rampage: false,
                perfectAccuracy: false,
                speedDemon: false,
                tankBuster: false,
                spitterHunter: false,
                fastZombieKiller: false,
                allRounder: false,
                veteran: false,
                legend: false,
                powerUpMaster: false,
                shieldMaster: false
            },
            statistics: {
                totalBulletsFired: 0,
                totalHits: 0,
                totalMisses: 0,
                accuracy: 0,
                fastestLevelTime: {},
                weaponsUsed: {
                    pistol: 0,
                    rifle: 0,
                    shotgun: 0,
                    smg: 0
                },
                zombiesKilledByType: {
                    normal: 0,
                    fast: 0,
                    tank: 0,
                    spitter: 0
                },
                perfectLevels: 0,
                noReloadLevels: 0,
                bossesKilled: 0,
                powerUpsCollected: 0,
                shieldTimeUsed: 0,
                consecutiveKills: 0,
                maxConsecutiveKills: 0,
                damageDealt: 0,
                damageTaken: 0,
                headshotKills: 0,
                longRangeKills: 0,
                levelCompletionTimes: {},
                perfectAccuracyLevels: 0,
                survivalTime: 0,
                rapidKills: 0,
                explosiveKills: 0
            },
            settings: {
                soundEnabled: true,
                musicEnabled: true,
                difficulty: 'normal',
                autoReload: false,
                showDamageNumbers: true,
                particleEffects: true
            }
        };
    }
    
    // 保存数据
    saveData(data) {
        try {
            const dataToSave = {
                ...this.defaultData,
                ...data,
                lastSaved: Date.now()
            };
            
            localStorage.setItem(this.storageKey, JSON.stringify(dataToSave));
            return true;
        } catch (error) {
            console.error('保存数据失败:', error);
            return false;
        }
    }
    
    // 加载数据
    loadData() {
        try {
            const saved = localStorage.getItem(this.storageKey);
            if (!saved) {
                return this.defaultData;
            }
            
            const data = JSON.parse(saved);
            
            // 版本检查和数据迁移
            if (data.version !== this.version) {
                return this.migrateData(data);
            }
            
            // 合并默认数据以确保新字段存在
            return { ...this.defaultData, ...data };
            
        } catch (error) {
            console.error('加载数据失败:', error);
            return this.defaultData;
        }
    }
    
    // 数据迁移
    migrateData(oldData) {
        console.log('迁移游戏数据...');
        const migratedData = { ...this.defaultData };
        
        // 保留重要的用户数据
        if (oldData.player) {
            migratedData.player = { ...migratedData.player, ...oldData.player };
        }
        
        if (oldData.progress) {
            migratedData.progress = { ...migratedData.progress, ...oldData.progress };
        }
        
        migratedData.version = this.version;
        this.saveData(migratedData);
        
        return migratedData;
    }
    
    // 保存游戏进度
    saveProgress(levelData) {
        const data = this.loadData();
        
        data.progress.currentLevel = levelData.level;
        data.progress.maxLevelReached = Math.max(data.progress.maxLevelReached, levelData.level);
        data.progress.lastPlayed = Date.now();
        
        if (levelData.completed) {
            if (!data.progress.levelsCompleted.includes(levelData.level)) {
                data.progress.levelsCompleted.push(levelData.level);
            }
        }
        
        this.saveData(data);
    }
    
    // 保存分数
    saveScore(score, levelScore, level) {
        const data = this.loadData();
        
        data.player.totalScore += score;
        data.player.highScore = Math.max(data.player.highScore, score);
        data.player.gamesPlayed++;
        
        // 保存关卡最佳时间
        if (levelScore && level) {
            const currentBest = data.statistics.fastestLevelTime[level];
            if (!currentBest || levelScore < currentBest) {
                data.statistics.fastestLevelTime[level] = levelScore;
            }
        }
        
        this.saveData(data);
        this.checkAchievements(data);
    }
    
    // 记录统计数据
    updateStatistics(statType, value = 1, subType = null) {
        try {
            window.debugLog && window.debugLog(`记录统计: ${statType}, 值: ${value}, 子类型: ${subType}`);
            
            const data = this.loadData();
            if (!data) {
                console.error('loadData 返回null，使用默认数据');
                throw new Error('无法加载数据');
            }
            
            // 确保必要的对象存在
            if (!data.statistics) {
                console.error('data.statistics 不存在，重新初始化');
                data.statistics = JSON.parse(JSON.stringify(this.defaultData.statistics));
            }
            
            // 确保statistics中的所有必要属性都存在
            const requiredStats = ['totalHits', 'totalMisses', 'totalBulletsFired', 'accuracy'];
            requiredStats.forEach(stat => {
                if (data.statistics[stat] === undefined || data.statistics[stat] === null) {
                    data.statistics[stat] = this.defaultData.statistics[stat] || 0;
                }
            });
            
            if (!data.player) {
                console.error('data.player 不存在，重新初始化');
                data.player = this.defaultData.player;
            }
            
            window.debugLog && window.debugLog('数据检查通过，开始更新统计');
        
        switch (statType) {
            case 'bulletFired':
                data.statistics.totalBulletsFired++;
                break;
                
            case 'hit':
                data.statistics.totalHits++;
                break;
                
            case 'miss':
                data.statistics.totalMisses++;
                break;
                
            case 'zombieKilled':
                data.player.totalKills++;
                if (subType && data.statistics.zombiesKilledByType[subType] !== undefined) {
                    data.statistics.zombiesKilledByType[subType]++;
                }
                // 连击统计
                data.statistics.consecutiveKills++;
                data.statistics.maxConsecutiveKills = Math.max(data.statistics.maxConsecutiveKills, data.statistics.consecutiveKills);
                break;
                
            case 'weaponUsed':
                if (subType && data.statistics.weaponsUsed[subType] !== undefined) {
                    data.statistics.weaponsUsed[subType]++;
                    data.player.favoriteWeapon = this.getFavoriteWeapon(data.statistics.weaponsUsed);
                }
                break;
                
            case 'bossKilled':
                data.statistics.bossesKilled++;
                break;
                
            case 'powerUpCollected':
                data.statistics.powerUpsCollected++;
                break;
                
            case 'shieldTimeUsed':
                data.statistics.shieldTimeUsed += value;
                break;
                
            case 'damageDealt':
                data.statistics.damageDealt += value;
                break;
                
            case 'damageTaken':
                data.statistics.damageTaken += value;
                // 重置连击
                data.statistics.consecutiveKills = 0;
                break;
                
            case 'headshotKill':
                data.statistics.headshotKills++;
                break;
                
            case 'longRangeKill':
                data.statistics.longRangeKills++;
                break;
                
            case 'perfectLevel':
                data.statistics.perfectLevels++;
                break;
                
            case 'noReloadLevel':
                data.statistics.noReloadLevels++;
                break;
                
            case 'perfectAccuracyLevel':
                data.statistics.perfectAccuracyLevels++;
                break;
                
            case 'survivalTime':
                data.statistics.survivalTime += value;
                break;
                
            case 'rapidKill':
                data.statistics.rapidKills++;
                break;
                
            case 'explosiveKill':
                data.statistics.explosiveKills++;
                break;
                
            case 'levelCompleted':
                if (subType && value) {
                    data.statistics.levelCompletionTimes[subType] = value;
                }
                break;
                
            case 'gameStarted':
                data.player.gamesPlayed++;
                break;
        }
        
            // 更新准确率 - 确保所有值都存在
            const totalHits = data.statistics.totalHits || 0;
            const totalMisses = data.statistics.totalMisses || 0;
            const totalShots = totalHits + totalMisses;
            if (totalShots > 0) {
                data.statistics.accuracy = (totalHits / totalShots * 100).toFixed(1);
            } else {
                data.statistics.accuracy = 0;
            }
            
            this.saveData(data);
            
            // 安全地检查成就
            try {
                this.checkAchievements(data);
            } catch (achievementError) {
                console.error('检查成就失败:', achievementError);
                window.debugLog && window.debugLog(`警告: 检查成就失败: ${achievementError.message}`);
            }
            
            window.debugLog && window.debugLog(`✓ 统计更新完成: ${statType}`);
        } catch (error) {
            console.error('updateStatistics 失败:', error);
            console.error('错误详情:', {
                statType: statType,
                value: value,
                subType: subType,
                error: error.message,
                stack: error.stack
            });
            window.debugLog && window.debugLog(`✗ 统计更新失败: ${statType} - ${error.message}`);
            // 不要让统计错误影响游戏运行
        }
    }
    
    // 获取最喜欢的武器
    getFavoriteWeapon(weaponsUsed) {
        let maxUsage = 0;
        let favorite = 'pistol';
        
        // 安全检查weaponsUsed是否为有效对象
        if (!weaponsUsed || typeof weaponsUsed !== 'object') {
            console.warn('getFavoriteWeapon: weaponsUsed无效，返回默认武器');
            return favorite;
        }
        
        try {
            for (const [weapon, usage] of Object.entries(weaponsUsed)) {
                if (typeof usage === 'number' && usage > maxUsage) {
                    maxUsage = usage;
                    favorite = weapon;
                }
            }
        } catch (error) {
            console.error('getFavoriteWeapon失败:', error);
        }
        
        return favorite;
    }
    
    // 检查成就
    checkAchievements(data) {
        try {
            if (!data || !data.achievements || !data.statistics) {
                console.error('checkAchievements: 数据不完整', data);
                return;
            }
            
            const achievements = data.achievements;
            const stats = data.statistics;
        
        // 基础成就
        if (!achievements.firstKill && data.player.totalKills > 0) {
            achievements.firstKill = true;
            this.showAchievement('首次击杀', '击杀你的第一只僵尸！', '🎯');
        }
        
        if (!achievements.levelComplete && data.progress.levelsCompleted.length > 0) {
            achievements.levelComplete = true;
            this.showAchievement('关卡完成', '完成你的第一个关卡！', '🏁');
        }
        
        // 武器相关成就
        if (!achievements.weaponMaster) {
            const weaponTypes = Object.keys(stats.weaponsUsed);
            const usedWeapons = weaponTypes.filter(weapon => stats.weaponsUsed[weapon] > 0);
            if (usedWeapons.length >= 4) {
                achievements.weaponMaster = true;
                this.showAchievement('武器大师', '使用过所有类型的武器！', '🔫');
            }
        }
        
        // 生存成就
        if (!achievements.survivor && data.progress.maxLevelReached >= 5) {
            achievements.survivor = true;
            this.showAchievement('生存者', '到达第5关！', '🛡️');
        }
        
        if (!achievements.unstoppable && data.progress.maxLevelReached >= 10) {
            achievements.unstoppable = true;
            this.showAchievement('无敌', '完成所有关卡！', '👑');
        }
        
        // 击杀成就
        if (!achievements.headHunter && data.player.totalKills >= 100) {
            achievements.headHunter = true;
            this.showAchievement('猎头者', '击杀100只僵尸！', '💀');
        }
        
        if (!achievements.berserker && data.player.totalKills >= 500) {
            achievements.berserker = true;
            this.showAchievement('狂战士', '击杀500只僵尸！', '⚔️');
        }
        
        if (!achievements.legend && data.player.totalKills >= 1000) {
            achievements.legend = true;
            this.showAchievement('传奇猎手', '击杀1000只僵尸！', '🌟');
        }
        
        // 精准射击成就
        if (!achievements.sharpShooter && parseFloat(stats.accuracy) >= 85) {
            achievements.sharpShooter = true;
            this.showAchievement('神枪手', '命中率达到85%！', '🎯');
        }
        
        if (!achievements.perfectAccuracy && parseFloat(stats.accuracy) >= 95) {
            achievements.perfectAccuracy = true;
            this.showAchievement('完美精准', '命中率达到95%！', '💎');
        }
        
        if (!achievements.oneShotOneKill && stats.headshotKills >= 50) {
            achievements.oneShotOneKill = true;
            this.showAchievement('一枪一个', '50次爆头击杀！', '💥');
        }
        
        // 连击成就
        if (!achievements.doubleDown && stats.maxConsecutiveKills >= 10) {
            achievements.doubleDown = true;
            this.showAchievement('双倍击杀', '连续击杀10个敌人！', '🔥');
        }
        
        if (!achievements.tripleKill && stats.maxConsecutiveKills >= 20) {
            achievements.tripleKill = true;
            this.showAchievement('三连杀', '连续击杀20个敌人！', '⚡');
        }
        
        if (!achievements.megaKill && stats.maxConsecutiveKills >= 50) {
            achievements.megaKill = true;
            this.showAchievement('超级连杀', '连续击杀50个敌人！', '💫');
        }
        
        if (!achievements.rampage && stats.maxConsecutiveKills >= 100) {
            achievements.rampage = true;
            this.showAchievement('大杀特杀', '连续击杀100个敌人！', '🌪️');
        }
        
        // Boss和特殊敌人成就
        if (!achievements.bossSlayer && stats.bossesKilled >= 1) {
            achievements.bossSlayer = true;
            this.showAchievement('Boss杀手', '击败你的第一个Boss！', '🗡️');
        }
        
        if (!achievements.tankBuster && stats.zombiesKilledByType.tank >= 50) {
            achievements.tankBuster = true;
            this.showAchievement('坦克克星', '击杀50个坦克僵尸！', '💣');
        }
        
        if (!achievements.spitterHunter && stats.zombiesKilledByType.spitter >= 30) {
            achievements.spitterHunter = true;
            this.showAchievement('喷射猎手', '击杀30个喷射僵尸！', '☣️');
        }
        
        if (!achievements.fastZombieKiller && stats.zombiesKilledByType.fast >= 100) {
            achievements.fastZombieKiller = true;
            this.showAchievement('速度杀手', '击杀100个快速僵尸！', '💨');
        }
        
        // 完美关卡成就
        if (!achievements.perfectLevel && stats.perfectLevels >= 1) {
            achievements.perfectLevel = true;
            this.showAchievement('完美关卡', '完美完成一个关卡（无伤害）！', '✨');
        }
        
        if (!achievements.invincible && stats.perfectLevels >= 5) {
            achievements.invincible = true;
            this.showAchievement('无敌战士', '完美完成5个关卡！', '🛡️');
        }
        
        // 技巧成就
        if (!achievements.noReload && stats.noReloadLevels >= 1) {
            achievements.noReload = true;
            this.showAchievement('不装弹大师', '在不装弹的情况下完成关卡！', '🔫');
        }
        
        if (!achievements.speedDemon && this.hasSpeedRunAchievement(stats.levelCompletionTimes)) {
            achievements.speedDemon = true;
            this.showAchievement('速度恶魔', '快速完成关卡！', '⚡');
        }
        
        // 收集成就
        if (!achievements.collector && stats.powerUpsCollected >= 50) {
            achievements.collector = true;
            this.showAchievement('收集家', '收集50个道具！', '📦');
        }
        
        if (!achievements.powerUpMaster && stats.powerUpsCollected >= 200) {
            achievements.powerUpMaster = true;
            this.showAchievement('道具大师', '收集200个道具！', '🎁');
        }
        
        if (!achievements.shieldMaster && stats.shieldTimeUsed >= 300000) { // 5分钟
            achievements.shieldMaster = true;
            this.showAchievement('护盾大师', '使用护盾超过5分钟！', '🛡️');
        }
        
        // 综合成就
        if (!achievements.allRounder && this.checkAllRounderAchievement(data)) {
            achievements.allRounder = true;
            this.showAchievement('全能战士', '在各个方面都表现出色！', '🏆');
        }
        
        if (!achievements.veteran && data.player.gamesPlayed >= 100) {
            achievements.veteran = true;
            this.showAchievement('老兵', '游戏100次！', '🎖️');
        }
        
        if (!achievements.chainKiller && stats.rapidKills >= 20) {
            achievements.chainKiller = true;
            this.showAchievement('连环杀手', '20次快速击杀！', '⚡');
        }
        
        this.saveData(data);
        } catch (error) {
            console.error('checkAchievements执行失败:', error);
        }
    }
    
    // 检查速度跑成就
    hasSpeedRunAchievement(levelTimes) {
        // 检查是否有任何关卡在很短时间内完成
        for (const [level, time] of Object.entries(levelTimes)) {
            if (time < 60000) { // 1分钟内完成
                return true;
            }
        }
        return false;
    }
    
    // 检查全能战士成就
    checkAllRounderAchievement(data) {
        const stats = data.statistics;
        return (
            data.player.totalKills >= 200 &&
            parseFloat(stats.accuracy) >= 75 &&
            stats.powerUpsCollected >= 30 &&
            data.progress.maxLevelReached >= 8 &&
            stats.bossesKilled >= 1
        );
    }
    
    // 显示成就
    showAchievement(title, description, icon = '🏆') {
        // 创建成就提示
        const achievement = document.createElement('div');
        achievement.className = 'achievement-popup';
        achievement.innerHTML = `
            <div class="achievement-content">
                <h3>${icon} 成就解锁</h3>
                <h4>${title}</h4>
                <p>${description}</p>
            </div>
        `;
        
        // 添加样式
        achievement.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #ffd700, #ffb347);
            color: #000;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(255, 215, 0, 0.5);
            z-index: 1000;
            animation: slideIn 0.5s ease-out;
            max-width: 300px;
        `;
        
        document.body.appendChild(achievement);
        
        // 3秒后移除
        setTimeout(() => {
            achievement.style.animation = 'slideOut 0.5s ease-in';
            setTimeout(() => {
                document.body.removeChild(achievement);
            }, 500);
        }, 3000);
    }
    
    // 获取排行榜数据
    getLeaderboard() {
        const data = this.loadData();
        return {
            highScore: data.player.highScore,
            totalKills: data.player.totalKills,
            gamesPlayed: data.player.gamesPlayed,
            maxLevel: data.progress.maxLevelReached,
            accuracy: data.statistics.accuracy,
            favoriteWeapon: data.player.favoriteWeapon
        };
    }
    
    // 重置数据
    resetData() {
        if (confirm('确定要重置所有游戏数据吗？此操作不可撤销！')) {
            localStorage.removeItem(this.storageKey);
            location.reload();
        }
    }
    
    // 导出数据
    exportData() {
        const data = this.loadData();
        const dataStr = JSON.stringify(data, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `zombie_game_save_${new Date().toISOString().split('T')[0]}.json`;
        link.click();
    }
    
    // 导入数据
    importData(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = JSON.parse(e.target.result);
                this.saveData(data);
                alert('数据导入成功！');
                location.reload();
            } catch (error) {
                alert('数据导入失败：文件格式错误');
            }
        };
        reader.readAsText(file);
    }
    
    // 获取游戏设置
    getSettings() {
        const data = this.loadData();
        return data.settings;
    }
    
    // 保存设置
    saveSettings(settings) {
        const data = this.loadData();
        data.settings = { ...data.settings, ...settings };
        this.saveData(data);
    }
}